<script>
export default {
    name:'user',
    data() {
      return {
        /* 状态，性别，部门树 */
        userStatusList:[],
        userSexList:[],
        depTreeList:[],
        // 部门树
        deptName:'',
        deptList:{
            deptId:'',
            data: [],
        },
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        filter:{
            userName:'',
            phonenumber:'',
            status:'',
            // 创建时间
            dateRange:'',
        },
        page: {
            pageNum: 1,
            pageSize: 10,
            total: 0
        },
        
        // 表单数据
        table:{
            data:[],
            loading:false
        }
      }
    },
    methods: {
      // 获取用户状态列表
      async queryUserStatusList(){
        let data = await this.$API.user.queryUserStatus()
        this.userStatusList = Object.freeze(data)
      },
      // 获取用户性别
      async queryUserSexList(){
        let data = await this.$API.user.queryUserSex()
         this.userSexList = Object.freeze(data)
      },
      // 获取部门树
      async queryDepTreeList(){
        try{
            let {code,data} = await this.$API.user.queryDepTree()
            if(+code !== 200){
                return
            }
            this.deptList.data = Object.freeze(data)
        }catch(_){}
      },
      // 获取用户列表
      async initData(){
        this.table.loading = true
        let {
                page: { pageNum, pageSize },
                filter: { userName, phonenumber, status,dateRange },
                deptList:{ deptId }
            } = this
        try{
            let { code, rows, total } =  await this.$API.user.queryUserData({
                pageNum,
                pageSize,
                userName,
                phonenumber,
                status,
                dateRange,
                deptId
            })
            if (+code !== 200) {
                rows = []
                total = 0
            }
            this.page.total = total
            this.table.data = Object.freeze(rows)

        }catch(_){}
        this.table.loading = false
      },

      // 更改用户状态
      async handleUserStatus(row){
        const { userId,status,userName } = row,
              text = status === '0'?'启用':'停用'
        try{
            await this.$confirm(`确定要${text} ${userName} 此用户吗?`, '系统提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            })
            let {code,msg}=await this.$API.user.updateUserStatus({
                    userId,
                    status
            })
            if(+code !== 200) return this.$message.error(msg)
            this.$message.success(`${text}成功`)

        }catch(_){}
      },
      // 搜索按钮
      triggerSearch(){
        this.page.pageNum = 1
        this.initData()
      },
      // 重置按钮
      resetFilter(){
        this.deptList.deptId = ''
        this.filter.userName = ''
        this.filter.phonenumber = ''
        this.filter.status = ''
        this.filter.dateRange = ''
        this.page.pageNum = 1
        this.initData()
      },

      // 筛选树节点
      filterNode(value, data){
        // 啥也没输入，全部显示
        if (!value) return true;
        return data.label.indexOf(value) !== -1;
      },
      // 点击树节点
      handleNodeClick({id}) {
        this.deptList.deptId = id
        this.initData()
      },
      

      // 将起始时间转化为URL编码的参数字符串
      formatterUrlString(dateRange){
        if(!Array.isArray(dateRange))return ''
        let beginTime = encodeURIComponent(`params[beginTime]`),
            endTime = encodeURIComponent(`params[endTime]`)
        
        let obj = {}
        obj[beginTime] = dateRange[0]
        obj[endTime] = dateRange[1]
        console.log(obj);
        
        return obj        
      },

    },
    created () {
        /* 获取状态，性别，部门树 */
        this.queryUserStatusList()
        this.queryUserSexList()
        this.queryDepTreeList()

        // 获取用户列表
        this.initData()
        
    },

    watch:{
        // 根据名称对树节点进行筛选操作
        deptName(newVal) {
            // filter为elemUI组件自己封装的方法
            this.$refs.tree.filter(newVal);
        }
    }
    
}
</script>

<template>
    <div class="user-box">
        <el-row :gutter="20">
            <!--部门数据-->
            <el-col class="head-left" :span="4" :xs="24">
                <el-input placeholder="请输入部门名称" size="small"  prefix-icon="el-icon-search" v-model.trim="deptName" clearable />
                <div class="tree-box">
                    <el-tree :data="deptList.data"
                    :node-key="deptList.data.id"
                    :props="defaultProps" ref="tree" 
                    :filter-node-method="filterNode"
                    @node-click="handleNodeClick" 
                    :expand-on-click-node="false" 
                    default-expand-all></el-tree>
                </div>
            </el-col>
            <!--用户数据-->
            <el-col :span="20" :xs="24">
                <el-form :model="filter" ref="queryForm" size="small" :inline="true" label-width="68px">
                    <el-form-item label="用户名称" prop="userName">
                        <el-input
                        v-model="filter.userName"
                        placeholder="请输入用户名称"
                        style="width: 240px"
                        @keyup.enter.native="handleQuery"
                        />
                    </el-form-item>
                    <el-form-item label="手机号码" prop="phonenumber">
                        <el-input
                        v-model="filter.phonenumber"
                        placeholder="请输入手机号码"
                        style="width: 240px"
                        @keyup.enter.native="handleQuery"
                        />
                    </el-form-item>
                    <el-form-item label="状态" prop="status">
                        <el-select
                        v-model="filter.status"
                        placeholder="用户状态"
                        style="width: 240px"
                        @change="initData"
                        clearable
                        >
                        <el-option v-for="item in userStatusList" :key="item.dictValue" :label="item.dictLabel" :value="item.dictValue" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="创建时间">
                        <el-date-picker
                            v-model="filter.dateRange"
                            style="width: 240px"
                            value-format="yyyy-MM-dd"
                            type="daterange"
                            range-separator="-"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期"
                        ></el-date-picker>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" icon="el-icon-search" size="small" @click="triggerSearch">搜索</el-button>
                        <el-button icon="el-icon-refresh" size="mini" @click="resetFilter">重置</el-button>
                    </el-form-item>
                </el-form>
                <el-table v-loading="table.loading" :data="table.data" :header-cell-style="{background:'#f9f9f9',color:'#606266'}" border>
                    <el-table-column type="selection" width="50" align="center" />
                    <el-table-column label="用户编号" align="center" key="userId" prop="userId"  />
                    <el-table-column label="用户名称" align="center" key="userName" prop="userName"  :show-overflow-tooltip="true" />
                    <el-table-column label="用户昵称" align="center" key="nickName" prop="nickName" :show-overflow-tooltip="true" />
                    <el-table-column label="部门" align="center" key="deptName" prop="dept.deptName" :show-overflow-tooltip="true" />
                    <el-table-column label="手机号码" align="center" key="phonenumber" prop="phonenumber"  width="120" />
                    <el-table-column label="状态" align="center" key="status">
                        <template slot-scope="scope">
                            <el-switch
                                v-model="scope.row.status"
                                active-value="0"
                                inactive-value="1"
                                @change="handleUserStatus(scope.row)"
                            ></el-switch>
                        </template>
                    </el-table-column>
                    <el-table-column label="创建时间" align="center" prop="createTime"  width="160"></el-table-column>
                    <el-table-column
                        label="操作"
                        align="center"
                        width="160"
                        class-name="small-padding fixed-width"
                    >
                        
                    </el-table-column>
                    <template #append>
                        <el-pagination background layout="total, sizes, prev, pager, next" hide-on-single-page :total="page.total" :current-page.sync="page.pageNum" :page-size.sync="page.pageSize" @size-change="initData" @current-change="initData">
                        </el-pagination>
                    </template>
                </el-table>
            </el-col>
        </el-row>

    </div>
</template>

<style lang="less" scoped>
.user-box{
    background: #fff;
    padding: 5px;

    .tree-box{
        padding-top: 20px;
    }
    .el-pagination {
    margin-top: 15px;
    text-align: right;
  }
}

</style>